//
//  HETeamDetailsViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2021/1/20.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HETeamDetailsViewController.h"
#import "HETeamModel.h"
#import "HEGhostButtonView.h"
#import "HETeamSpecView.h"
#import "HEDoctorServerComfireViewController.h"
#import "HEHTMLStringViewController.h"

@interface HETeamDetailsViewController ()<HETeamSpecViewDelegate>

@property (nonatomic, strong) HETeamModel *teamModel;

@property (nonatomic, strong) UIScrollView *scrollView;
// 约束参照视图,也是容器视图
@property (nonatomic, strong) UIView *contentView;
 
@property (nonatomic, strong) HEGhostButtonView *tabbarView;

@property (nonatomic, strong) HETeamSpecView *specView;

@property (nonatomic, strong) UIImageView *backView;

@property (nonatomic, strong) NSString *skuDetailURL;

@property (nonatomic, strong) NSString *userIdCrad;

@end

@implementation HETeamDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    if ([DYTools isBlankString:_detailImgURL]) {
        [self initTeamDetail];
    }else {
        [self initDetailImgPage];
    }
}

- (void)initDetailImgPage {
    self.title = @"服务详请";

    [self initUI];
    
    [self.backView sd_setImageWithURL:[NSURL URLWithString: _detailImgURL] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        
        CGFloat scale = self.backView.image.size.width / self.backView.image.size.height;
        CGFloat height = (KScreenWidth - 20) / scale;
        
        [self.backView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self.contentView);
            make.right.equalTo(self.contentView).offset(-10);
            make.left.equalTo(self.contentView).offset(10);
            make.height.offset(height);
        }];
    }];
}

- (void)initTeamDetail {
    self.title = @"团队详请";
    
    [self initUI];

    [self loadData];
    [self initTabBarView];
}

- (void)loadData {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_teamId forKey:@"id"];

    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KTeamInfo parameters:dict success:^(id  _Nonnull responseObject) {
 
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        weakSelf.teamModel = [HETeamModel mj_objectWithKeyValues: response.data];
        if(self.teamModel.teamAdvert) {
            [weakSelf.backView sd_setImageWithURL:[NSURL URLWithString:self.teamModel.teamAdvert] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                
                CGFloat scale = weakSelf.backView.image.size.width / weakSelf.backView.image.size.height;
                CGFloat height = (KScreenWidth - 20) / scale;
                
                [weakSelf.backView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.bottom.equalTo(weakSelf.contentView);
                    make.right.equalTo(weakSelf.contentView).offset(-10);
                    make.left.equalTo(weakSelf.contentView).offset(10);
                    make.height.offset(height);
                }];
            }];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)initUI {
    
    // 1. 添加scrollView
    [self.view addSubview:self.scrollView];
    // 2. 添加参照视图
    [self.scrollView addSubview:self.contentView];
    
    UIImageView *backView = [UIImageView new];
    backView.contentMode = UIViewContentModeScaleAspectFill;
//    backView.image = IMAGE_NAMED(@"teamDetail");
    [_contentView addSubview:backView];
    _backView = backView;
    
}

- (void)initTabBarView {
    
    _tabbarView = [HEGhostButtonView new];
    [_tabbarView setupTitle: @"立即开通"];
    _tabbarView.backgroundColor = UIColor.clearColor;
    [self.view addSubview: _tabbarView];
    
    [_tabbarView tapBlock:^{
        [self.specView show];
    }];
    
    [_tabbarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_offset(60);
        make.bottom.equalTo(self.view).offset(-10);
    }];
}
  

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // 布局子控件
    // 设置scrollView约束
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(ZXNavBarHeight, 0, 0, 0));
    }];
    
    // 设置参照视图的约束
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
//        make.height.greaterThanOrEqualTo(@0.0f);
    }];
}

#pragma mark - HETeamSpecViewDelegate
- (void)seeDetailsVC {
    [_specView hiddenView];
    HEHTMLStringViewController *vc = [HEHTMLStringViewController new];
    vc.htmlStr = self.skuDetailURL;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - getters
// scrollView
- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = KWhiteColor;
    }
    return _scrollView;
}

// 约束参照视图
- (UIView *)contentView {
    if (_contentView == nil) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = KWhiteColor;
    }
    return _contentView;
}

 
- (HETeamSpecView *)specView {
    if (!_specView) {
        NSMutableArray *allSepec = [NSMutableArray array];

        // 获取不同service
        NSMutableArray *section = @[].mutableCopy;
        NSMutableArray *serviceKeyArr = @[].mutableCopy;
        NSMutableArray *compareArr = [NSMutableArray array];

        for (HETeamServiceModel *attr in _teamModel.services) {
            NSString *stype = [NSString stringWithFormat:@"%ld", attr.serviceType];
            if (![serviceKeyArr containsObject: stype]) {
                [serviceKeyArr addObject:stype];
            }
            
            // 组装比较模型
            compareSepecModel *compareM = [[compareSepecModel alloc]init];
            compareM.goodspriceid = [attr.id integerValue];
            compareM.spec_price = attr.totalFee;
            compareM.spec_pic = attr.serviceIcon;
//            compareM.stock = compareModel.stock;
            compareM.matchStr = attr.serviceName;
            
            if ([@"0" isEqualToString: stype]) {
                compareM.org_price = attr.baseFee;
            }
            
            [compareArr addObject:compareM];
        }
        
        // 对数组进行排序（升序）
        serviceKeyArr = [serviceKeyArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2];
        }];
        
        for (NSString *serviceType in serviceKeyArr) {
            NSMutableArray <HETeamServiceModel *>*services = @[].mutableCopy;
            for (HETeamServiceModel *attr in _teamModel.services) {
                NSString *stype = [NSString stringWithFormat:@"%ld", attr.serviceType];
                if ([serviceType isEqualToString:stype]) {
                    [services addObject:attr];
                }
            }
            [section addObject:services];
            
            // 转换数据
            SepecModel *goodSpec = [[SepecModel alloc]init];
            
            // head名称赋值
            if ([@"0" isEqualToString:serviceType]) {
                goodSpec.name_sepec = _teamModel.teamName;
                goodSpec.name_sepec = @"线上签约";
            }else {
//                goodSpec.name_sepec = services.firstObject.serviceCategory;
                goodSpec.name_sepec = @"护理上门";
            }
            
            NSMutableArray *subSpecArr = @[].mutableCopy;
            for (HETeamServiceModel *attr in services) {
                // 商品id赋值
                goodSpec.id_sepec = [attr.serviceId integerValue];
                
                // 创建属性
                SepecDetailModel *sepecmodel = NULL;

                if ([@"0" isEqualToString: serviceType]) {
                    if (![DYTools isBlankString:attr.serviceContent]) {
                        self.skuDetailURL = attr.serviceContent;
                    }
                    sepecmodel = [[SepecDetailModel alloc] initWithName:[NSString stringWithFormat:@"%@%@",attr.attrName, attr.unit] font:DYFont(15)];
                }else {
                    sepecmodel = [[SepecDetailModel alloc] initWithName: attr.serviceName font:DYFont(15)];
                    sepecmodel.desc = attr.serviceContent;
                }
                sepecmodel.id_sepec = attr.id;
                [subSpecArr addObject:sepecmodel];
            }
            goodSpec.arr_sepec = subSpecArr;

            [allSepec addObject:goodSpec];
        }
        

        HETeamSpecView *seleView = [HETeamSpecView selectSpecViewWithdataArr:allSepec];
        seleView.goods = _teamModel;
        seleView.comparedataArr = compareArr;
        seleView.delegate = self;
        seleView.showDetailBtn = YES;

        KWeakSelf
        seleView.finishSelectedBlock = ^(SepecDetailModel *model) {
            
            if (![[UserManager sharedUserManager] getUserInfo].verifyStatus) {
                    HERealNameAuthAlterController *vc = [HERealNameAuthAlterController new];
                    [weakSelf.view addSubview:vc.view];
                return;
            }
            
            HETeamServiceModel *serverModel = [self getTeamServer:model.id_sepec];
            
            if (serverModel.serviceType == 0) {
                HEDoctorServerComfireViewController *vc = [HEDoctorServerComfireViewController new];
                HEServerComfireModel *comfireModel = [HEServerComfireModel new];
                comfireModel.icon_url = weakSelf.teamModel.teamIcon;
                comfireModel.topStr = weakSelf.teamModel.teamName;
                comfireModel.middleStr = weakSelf.teamModel.teamDeptName;
                comfireModel.bottomStr = weakSelf.teamModel.teamHospitalName;
                comfireModel.payParams = @[serverModel.serviceName,
                                           [NSString stringWithFormat:@"￥%@/%@%@", [NSDecimalNumber rounding: serverModel.totalFee afterPoint:2], serverModel.attrName, serverModel.unit]];
                
                HECreateOrderRequest *request = [HECreateOrderRequest new];
                request.orderType = HEOrderTypeGeneral;
//                request.doctor_id = weakSelf.teamModel.teamManager;
                request.total = 1;
                request.goodsId = serverModel.serviceId;
                request.channel = HEChannelTypeDoctorTeam;
                request.skuId = [serverModel.attrId integerValue];
                request.source = HEOrderSourceTypeiOS;
                request.type = HESubmitPreviewTypeByGoodsDetails;
                request.team_id = weakSelf.teamId;
                request.appSource = KAppSource;

                HEExtraDoctorInfoModel *extra = [HEExtraDoctorInfoModel new];
                extra.serviceLength = serverModel.attrName;
                extra.order_type = HEChannelTypeDoctorTeam;
                extra.team_info = [TeamInfo new];
                
                extra.team_info.teamName = weakSelf.teamModel.teamName;
                extra.team_info.teamDept = weakSelf.teamModel.teamDept;
                extra.team_info.teamHospital = weakSelf.teamModel.teamHospital;
                extra.team_info.latitude = weakSelf.teamModel.latitude;
                extra.team_info.longitude = weakSelf.teamModel.longitude;
                extra.team_info.teamManagerName = weakSelf.teamModel.teamManagerName;
                extra.team_info.teamState = weakSelf.teamModel.teamState;
                extra.team_info.teamDesc = weakSelf.teamModel.teamDesc;
                extra.team_info.teamIcon = weakSelf.teamModel.teamIcon;
                extra.team_info.teamDeptName = weakSelf.teamModel.teamDeptName;
                extra.team_info.teamHospitalName = weakSelf.teamModel.teamHospitalName;
                extra.team_info.teamManager = weakSelf.teamModel.teamManager;
                extra.team_info.id = weakSelf.teamModel.id;

                request.extras = [extra mj_JSONString];
                
                vc.comfireModel = comfireModel;
                vc.orderRequest = request;
                vc.price = serverModel.totalFee;
                vc.isSelectSign = YES;
                vc.isShowPrefer = YES;
                vc.serviceCategoryId = serverModel.serviceCategoryId;
                vc.visit = weakSelf.teamModel.visit;
                [self.navigationController pushViewController:vc animated:YES];
            }else {
                [self productJump: serverModel];
            }
        };

        _specView = seleView;
    }
    
    return _specView;
}

- (HETeamServiceModel *)getTeamServer:(NSString *)idStr {
    for (HETeamServiceModel *attr in _teamModel.services) {
         if ([idStr isEqualToString: attr.id]) {
             return attr;
        }
    }
    return NULL;
}

#pragma mark -
- (void)productJump:(HETeamServiceModel *)serverModel {
    if (self.userIdCrad != NULL) {
        [self intoWxminiServer: serverModel];
        return;
    }
     
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KuserSfz parameters:@{} success:^(id  _Nonnull responseObject) {
        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            self.userIdCrad = response.data;
            [self intoWxminiServer: serverModel];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)intoWxminiServer:(HETeamServiceModel *)serverModel {
    
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:serverModel.outHospitalId forKey:@"hospitalId"];
    [params setValue:serverModel.serviceId forKey:@"welfareInfoId"];
    [params setValue:serverModel.outServiceId forKey:@"id"];
    [params setValue:@"app" forKey:@"type"];
    [params setValue:self.teamModel.teamName forKey:@"teamName"];
    [params setValue:self.teamId forKey:@"teamId"];
    [params setValue:self.teamModel.rebate forKey:@"rebate"];

    NSMutableDictionary *patientData = [NSMutableDictionary dictionary];
    [patientData setValue:user.id forKey:@"id"];
    [patientData setValue:user.username forKey:@"phone"];
    [patientData setValue:[NSNumber numberWithInteger:user.sex] forKey:@"sex"];
    [patientData setValue:user.realname forKey:@"userName"];
    [patientData setValue:self.userIdCrad forKey:@"idCard"];

    [params setValue:patientData forKey:@"patientData"];

    NSString *encodeData = [[params mj_JSONString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    encodeData = [[params mj_JSONString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *path = [NSString stringWithFormat:@"%@%@%@", @"packageA/evaluate/index" , @"?source=app&query=", encodeData];
    if ([WXApi isWXAppInstalled]) { //先判断是否安装微信
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName = serverModel.outOriginalId;  //拉起的小程序的username-原始ID
    launchMiniProgramReq.path = path; //拉起小程序页面的可带参路径，不填默认拉起小程序首页
        launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        if (!success) {
            [Dialog toastBottom:@"无法唤起小程序"];
        }
    }];
    }else{
        //提示用户没有安装微信，不能拉起小程序
    }
}

@end
